import { observable, action, toJS } from 'mobx';
import { message, Button, Modal } from 'antd';
import { WeaLocaleProvider, WeaTools } from 'ecCom';
import _ from 'lodash';
const getLabel = WeaLocaleProvider.getLabel;
const formatMultiLang = WeaLocaleProvider.formatMultiLang;
import { getFieldAssign, listDataSetTableFields, saveFieldAssign, deleteFieldAssign, getCheckSql } from "../../apis/dataset";
import React from 'react';
import DialogStore from ".";
import ConditionSetStore from './ConditionSetStore';
import ExcelCellSelect from '../../components/dialog/ExcelCellSelect'
import { each } from 'lodash';
import getCellIndex from '../../utils/getCellIndex';
import getCellName from '../../utils/getCellName';

export default class FieldAssignDialogStore extends DialogStore {
    @observable conditionSetStore = new ConditionSetStore();//条件参数
    @observable pageid = "";
    @observable name = "";
    @observable dataSet = "";
    @observable type = "";
    @observable dataSetList = [];
    // @observable dataSetMap = {};
    @observable fieldOptions = [];//可编辑列表数据库字段选择
    @observable targetFieldOptions = [];//目标字段数据源条件字段选择
    @observable tableOptions = [];//数据源中所有数据表
    @observable columns = [];
    @observable datas = [];//赋值操作可编辑列表
    @observable conditionInfo = {};
    @observable typeOptions = [{ key: "0", showname: "无条件赋值" }, { key: "1", showname: "满足特定条件赋值" }];
    @observable width = 1000;
    @observable dialogType = 'normal';
    @observable faMenuVisible = false;
    @observable nameError;
    @observable dataSetError;
    @observable triggerType = "0";//触发明细类型

    constructor() {
        super();
        this.style = {};
        //this.buttons = [<Button ecId={`${this && this.props && this.props.ecId || ''}_Button@23ix9a@save`} onClick={this.onSave} type="primary">{getLabel(30986, '保存')}</Button>,
        //<Button ecId={`${this && this.props && this.props.ecId || ''}_Button@qhi7vd@clean`} onClick={this.clean} type="primary">{getLabel('508532', '清空条件')}</Button>,
        //    <Button ecId={`${this && this.props && this.props.ecId || ''}_Button@ljmrkk@checkSQL`} onClick={this.checkSQL} type="primary">{getLabel('515659', '检测条件')}</Button>,
        //<Button ecId={`${this && this.props && this.props.ecId || ''}_Button@wkqe1q@cancel`} onClick={this.hideDialog} type="primary">{getLabel('31129', '取消')}</Button>]
    }

    @action hideDialog = () => {
        this.hide();
        //按钮点亮
        const edcExcelDesignerStore = this.parent();
        if (edcExcelDesignerStore) {
            edcExcelDesignerStore.readonly = false;
            //获取父store
            const appDesignerStore = edcExcelDesignerStore.parent();
            if (edcExcelDesignerStore) {
                appDesignerStore.readonly = false;
            }
        }
    }

    @action openDialog = () => {
        this.open();
        //按钮置灰
        const edcExcelDesignerStore = this.parent();
        if (edcExcelDesignerStore) {
            edcExcelDesignerStore.readonly = true;
            //获取父store
            const appDesignerStore = edcExcelDesignerStore.parent();
            if (edcExcelDesignerStore) {
                appDesignerStore.readonly = true;
            }
        }
    }

    @action
    onSave = () => {
        if (!this.name) {
            this.nameError.showError();
            return;
        }
        if (!this.dataSet) {
            this.dataSetError.showError();
            return;
        }
        const datasArr = toJS(this.datas);
        //赋值操作编辑列表必填校验
        let isRequiredWarn = false;
        datasArr.forEach(data => {
            const { dbfield, showname } = data;
            if (!dbfield || dbfield == "" || !showname || showname == "") {
                isRequiredWarn = true;
            }
        });
        if (isRequiredWarn) {
            message.warning(getLabel('512024', '请检查赋值操作必填项是否都已填写'), 3);
        } else if (this.datas.length == 0) {
            message.warning(getLabel('511953', '请至少设置一条赋值操作'), 3);
        } else if (this.type == "1") {
            const conditionSetStore = this.conditionSetStore;
            conditionSetStore.getShowSql();
            const { conditionInfo, editArr, ruleSql, isChange, targetValue, refObj } = conditionSetStore;
            const { conditiontype, conditionsql2 } = conditionInfo;

            if (conditiontype == 1) {
                if (editArr.length > 0) {
                    message.error(getLabel('513499', '存在字段处于编辑状态，请编辑好后再进行保存操作'));
                    return;
                }
                if (isChange == true && targetValue != "") {
                    Modal.confirm({
                        title: getLabel('513500', '当前目标字段的值未添加到条件中，是否继续保存'),
                        onOk: () => {
                            if (ruleSql == "") {
                                message.error(getLabel('515656', '条件') + getLabel('513479', '不能为空!'));
                                return;
                            }
                            this.doSaveCondition();
                        },
                        onCancel() {
                            return;
                        },
                    });
                } else {
                    if (ruleSql == "") {
                        message.error(getLabel('515656', '条件') + getLabel('513479', '不能为空!'));
                        return;
                    }
                    this.doSaveCondition();
                }
            } else {
                if (_.trim(formatMultiLang(conditionsql2)) == "") {
                    for (let key in refObj) {
                        if (key == "sql_") {
                            const domkeyRef = refObj[key];
                            domkeyRef.showError();
                            return;
                        }
                    }
                } else {
                    this.doSaveCondition();
                }
            }
        } else {
            this.doSaveCondition();
        }
    }

    doSaveCondition() {
        if (this.type == "1") {
            const conditionSetStore = this.conditionSetStore;
            const { conditionInfo, ruleSql, ruleSqlText } = conditionSetStore;
            const { conditiontype, conditionsql2 } = conditionInfo;
            let Base64 = WeaTools.Base64;
            let sql = Base64.encode(ruleSql);
            let sqlText = Base64.encode(ruleSqlText);
            let sql2 = Base64.encode(conditionsql2);
            if (conditiontype == 1) {
                this.conditionInfo = {
                    root: conditionSetStore.root,
                    conditionsql: sql,
                    conditiontext: sqlText,
                    conditiontype: "1"
                };
            } else {
                this.conditionInfo = {
                    conditionsql2: sql2,
                    conditiontype: conditiontype
                };
            }
        } else {
            this.conditionInfo = {};
        }
        saveFieldAssign({
            pageid: this.pageid,
            id: this.id,
            name: this.name,
            dsid: this.dataSet,
            type: this.type,
            triggerType: this.triggerType,//触发明细类型
            conditionInfo: JSON.stringify(this.conditionInfo),
            fieldRelations: JSON.stringify(this.datas)
        }).then(() => {
            this.hideDialog();
            message.success(getLabel('502231', '保存成功'));
            if (this.reloadPageFieldAssignList) {
                this.reloadPageFieldAssignList();
            }
        })

    }

    @action
    clean = () => {
        if (this.type == "1") {
            Modal.confirm({
                title: getLabel('515714', '确定清空所有条件？'),
                onOk: () => {
                    this.conditionInfo = {
                        root: {},
                        conditionsql: "",
                        conditiontext: "",
                        conditiontype: "1"
                    };
                    this.initConditionSet(this.type);
                    message.success(getLabel(83885, "操作成功!"));
                },
                onCancel() { },
            });
        } else {
            message.warning(getLabel('511954', '当前选中无条件赋值，不需要清空'), 3);
        }
    }

    @action deleteFieldAssign = (id) => {
        Modal.confirm({
            content: getLabel('505984', '是否确认删除？'),
            onOk: () => {
                deleteFieldAssign(id).then(() => {
                    // this.hide();
                    message.success(getLabel('505985', '删除成功'));
                    if (this.reloadPageFieldAssignList) {
                        this.reloadPageFieldAssignList();
                    }
                });
            },
            onCancel() { },
        });
    }

    @action newFieldAssign = (pageid, pageName) => {
        if (!pageid) {
            message.error(getLabel('508435', '请先保存EXCEL，再创建字段赋值'));
            return;
        }
        const parent = this.parent();
        if (parent && parent.dataSourceList) {
            const dataSetList = parent.dataSourceList.map(d => ({ key: d.uuid, showname: d.name, disabled: d.disabled }));
            this.dataSetList = dataSetList;
        }
        this.pageid = pageid;
        this.pageName = pageName;
        this.title = getLabel('508437', '新建字段赋值');
        this.id = "";
        this.name = "";
        this.faMenuVisible = false;
        this.openDialog();
        const clientWidth = document.documentElement.clientWidth - 200;
        const clientHeight = document.documentElement.clientHeight - 100;
        this.style.width = clientWidth;
        this.heihgt = clientHeight;
        this.datas = [];
        this.type = "0";
        this.triggerType = "0";//触发明细类型
        this.dataSet = "";
        this.conditionInfo = {
            root: {},
            conditionsql: "",
            conditiontext: "",
            conditiontype: "1"
        };
        //columns,conditionSetStore
        this.columns = [];
        // this.targetFieldOptions = [];
        // this.targetValueOptions = [];
        // this.tableOptions = [];
        //初始化
        this.conditionSetStore.initCondition(this.conditionInfo, this.targetFieldOptions, [], this.tableOptions);
    }

    @action openFieldAssign = (pageid, pageName, id) => {
        this.pageid = pageid;
        this.pageName = pageName;
        this.id = id;
        this.title = getLabel('507808', '字段赋值') + ":"
        this.faMenuVisible = false;
        this.openDialog();
        const clientWidth = document.documentElement.clientWidth - 200;
        const clientHeight = document.documentElement.clientHeight - 100;
        this.style.width = clientWidth;
        this.style.width = clientWidth;
        this.heihgt = clientHeight;
        getFieldAssign(id).then(this.setFieldAssign);
    }

    @action
    setFieldAssign = (data) => {
        const { name, dsid, fieldRelations, type, triggerType, conditionInfo } = data;
        if (fieldRelations) {
            const a = JSON.parse(fieldRelations);
            this.datas = a.map(f => ({ ...f, randomkey: this.createRandomKey(8) }));
        }
        this.name = name;
        this.dataSet = dsid;
        this.triggerType = triggerType;
        if (conditionInfo) {
            this.conditionInfo = JSON.parse(conditionInfo);
        }
        const parent = this.parent();
        if (parent && parent.dataSourceList) {
            const dataSetList = parent.dataSourceList.map(d => ({ key: d.uuid, showname: d.name }));
            // this.tableOptions = [];
            this.init(dsid, type);
            this.dataSetList = dataSetList;
        }
    }

    /**
     * 切换数据源及其初始化赋值
     */
    @action changeDataSet = (ds) => {
        this.dataSet = ds;
        this.datas = [];
        // this.fieldOptions = [];
        // this.targetFieldOptions = [];
        // this.tableOptions = [];
        this.conditionInfo = {
            root: {},
            conditionsql: "",
            conditiontext: "",
            conditiontype: "1"
        };
        this.type = '0';
        this.init(this.dataSet, this.type);
    }


    @action changeName = (name) => {
        this.name = name;
    }

    /**
     * 切换切赋值条件类型及其初始化赋值
     */
    @action changeSelect(value) {
        this.conditionInfo = {
            root: {},
            conditionsql: "",
            conditiontext: "",
            conditiontype: "1"
        };
        this.initConditionSet(value);
    }

    /**
     * 根据type选择初始化数据
     */
    initConditionSet(type) {
        //切换赋值条件类型,能够选择时必定已经选择了数据源
        if (type === '1') {
            //关联表格字段
            const targetValueOptions = this.getTargetValueOptions(true);
            //初始化条件赋值组件
            this.conditionSetStore.initCondition(this.conditionInfo, this.targetFieldOptions, targetValueOptions, this.tableOptions);
        } else {
            this.triggerType = "0";
        }
        this.type = type;
    }

    @action init = (dsid, type) => {
        listDataSetTableFields(dsid).then(result => {
            const tablelist = result;
            this.fieldOptions = [];
            this.targetFieldOptions = [];
            this.tableOptions = [];
            if (tablelist && tablelist.length > 0) {
                tablelist.forEach(t => {
                    this.tableOptions.push(t.showname);
                    if (t.children) {
                        this.fieldOptions = [...this.fieldOptions, ...t.children.map(d => ({ key: t.key + '.' + d.key, showname: t.showname + '.' + d.showname }))];
                        this.targetFieldOptions = [...this.targetFieldOptions, ...t.children.map(d => ({ key: '$' + t.showname + '$.' + d.key, showname: t.showname + '.' + d.showname }))];
                    }
                });
                this.getColumns();
            }
            this.initConditionSet(type);
        });
    }

    @action getColumns = () => {
        const targetValueOptions = this.getTargetValueOptions();
        this.columns = [
            {
                title: getLabel('508533', '表格字段'),
                dataIndex: 'dataIndex1',
                width: '50%',
                com: [
                    <ExcelCellSelect ecId={`${this && this.props && this.props.ecId || ''}_ExcelCellSelect@ulccdi@dataIndex1`}
                        setActiveCell={this.setActiveCell}
                        // options={[{ key: 'empty', showname: <span>&nbsp;</span> }, { key: '1', showname: '字段1' }]}
                        options={[{ key: 'empty', showname: <span>&nbsp;</span> }, ...targetValueOptions.slice()]}
                        onChangeSize={this.onChangeSize}
                    />

                ],
            },
            {
                title: getLabel('508534', '数据库字段'),
                dataIndex: 'dbfield',
                width: '50%',
                com: [
                    {
                        viewAttr: 3,
                        type: 'SELECT',
                        key: 'dbfield',
                        style: {
                            width: '380px',
                            left: '25px'
                        },
                        options: this.fieldOptions.slice(),
                        optionFilterProp: 'children',
                        showSearch: true
                    }
                ]
            }
        ];
    }

    /**
     * 可编辑列表数据变化事件
     */
    @action
    onChange = (datas) => {
        this.datas = datas;
    }

    @action
    onChangeSize = (dialogType, excelCellSelect) => {
        this.dialogType = dialogType;
        this.width = dialogType === 'normal' ? 1000 : 520;
        this.parent().excelCellSelect = excelCellSelect;
    }

    @action
    willAdd = (datas) => {
        setTimeout(() => {
            $('.ant-table-body').scrollTop($('.ant-table-body')[0].scrollHeight);
        }, 50);
        return datas;
    };

    createRandomKey = (length) => {
        return Math.random().toString(36).substr(2, length);
    }

    @action faShowMenu = (visible) => {
        this.faMenuVisible = visible;
    }

    /**
     * 获取表格字段
     */
    getTargetValueOptions = (isCondition) => {
        let targetValueOptions = [];
        const parent = this.parent();
        if (parent && parent.workbook) {
            const workbook = parent.workbook.toJSON();
            const { sheets } = workbook;
            if (sheets) {
                each(sheets, (sheet, sheetKey) => {
                    const { data, tables } = sheet;
                    if (data) {
                        const { dataTable } = data;
                        if (dataTable) {
                            each(dataTable, (o) => {
                                each(o, (obj) => {
                                    const { bindingPath, style } = obj
                                    if (style) {
                                        const { cellType } = style;
                                        if (cellType) {
                                            const { label, fieldName, detailIndex } = cellType;
                                            if (label && fieldName) {
                                                if (!detailIndex || detailIndex === void 0) {
                                                    if (bindingPath) {
                                                        targetValueOptions.push({
                                                            key: isCondition ? `$${bindingPath}$` : `${bindingPath}`,
                                                            showname: `${sheetKey}.${getLabel('514299', '主表')}.${fieldName}(${label})`
                                                        });
                                                    }
                                                } else {
                                                    targetValueOptions.push({
                                                        key: isCondition ? `$${sheetKey}.detail_${detailIndex}.${fieldName}$` : `${sheetKey}.detail_${detailIndex}.${fieldName}`,
                                                        showname: `${sheetKey}.${getLabel('514300', '明细')}${detailIndex}.${fieldName}(${label})`
                                                    });
                                                }
                                            }
                                        }
                                    }
                                });
                            });

                        }
                    }
                });
            }
        }
        return targetValueOptions;
    }

    /**
     * 选择明细联动类型
     */
    @action changeTriggerType(value) {
        this.triggerType = value;
    }

    @action checkSQL = () => {
        if (!this.dataSet) {
            this.dataSetError.showError();
            return;
        }
        if (this.type == "1") {
            const conditionSetStore = this.conditionSetStore;
            conditionSetStore.getShowSql();
            const { conditionInfo, editArr, ruleSql, isChange, targetValue, refObj } = conditionSetStore;
            const { conditiontype, conditionsql2 } = conditionInfo;

            if (conditiontype == 1) {
                if (editArr.length > 0) {
                    message.error(getLabel('515661', '存在字段处于编辑状态，请编辑好后再进行操作'));
                    return;
                }
                if (isChange == true && targetValue != "") {
                    Modal.confirm({
                        title: getLabel('515660', '当前目标字段的值未添加到条件中，是否继续操作'),
                        onOk: () => {
                            if (ruleSql == "") {
                                message.error(getLabel('515656', '条件') + getLabel('513479', '不能为空!'));
                                return;
                            }
                            this.doCheckSQL();
                        },
                        onCancel() {
                            return;
                        },
                    });
                } else {
                    if (ruleSql == "") {
                        message.error(getLabel('515656', '条件') + getLabel('513479', '不能为空!'));
                        return;
                    }
                    this.doCheckSQL();
                }
            } else {
                if (_.trim(formatMultiLang(conditionsql2)) == "") {
                    for (let key in refObj) {
                        if (key == "sql_") {
                            const domkeyRef = refObj[key];
                            domkeyRef.showError();
                            return;
                        }
                    }
                } else {
                    this.doCheckSQL();
                }
            }
        } else {
            message.warning(getLabel('515720', '当前选中无条件赋值，无法检测条件'));
        }
    }

    doCheckSQL = () => {
        const conditionSetStore = this.conditionSetStore;
        const { conditionInfo, ruleSql } = conditionSetStore;
        const { conditiontype, conditionsql2 } = conditionInfo;
        let Base64 = WeaTools.Base64;
        let sql = Base64.encode(ruleSql);
        let sql2 = Base64.encode(conditionsql2);
        getCheckSql({
            pageid: this.pageid,
            sql: conditiontype == 1 ? sql : sql2,
            dsid: this.dataSet,
        }).then(data => {
            if (data.flag == '1') {
                message.success(getLabel('515657', '条件检测通过'));
            } else {
                Modal.error({
                    title: getLabel('515680', '错误条件'),
                    content: (
                        <div className='wea-error-sql'>
                            <div>{getLabel('515658', '条件检测未通过，具体SQL如下：')}</div>
                            {data.sql}
                        </div>
                    ),
                    onOk() { },
                    width: 800
                });
            }
        })
    }

    setActiveCell = (field, fieldtype) => {
        let fieldIndex = {};
        if (field) {
            const [sheetName, fieldOrDetail, detailField] = field.split('.');
            if (detailField) {
                const detailMark = `${sheetName}.${fieldOrDetail}.0.${detailField}`;
                fieldIndex = this.getFieldIndex(detailMark);
            } else {
                if (fieldtype == 'cellfield') {
                    const cellIndex = getCellIndex(fieldOrDetail);
                    const { rowIndex, colIndex } = cellIndex;
                    if (sheetName) {
                        const parent = this.parent();
                        if (parent && parent.workbook) {
                            const sheet = parent.workbook.getSheetFromName(sheetName);
                            fieldIndex = { sheet, row: rowIndex, col: colIndex };
                        }
                    }
                } else {
                    fieldIndex = this.getFieldIndex(field);
                }

            }
        }
        const { sheet, row, col } = fieldIndex;
        if (fieldIndex && sheet && row && col) {
            sheet.setActiveCell(row, col);
            const table = sheet.tables.find(row, col);
            const parent = this.parent();
            if (parent) {
                if (table) {
                    parent.activeCellName = `${getCellName(row, col)}(${table.name()})`;
                } else {
                    parent.activeCellName = getCellName(row, col);
                }
            }
        }
    }

    /**
    * 获取字段的行列索引
    */
    getFieldIndex = (fieldName) => {
        const [sheetName, fieldOrDetail, detailRow, detailField] = fieldName.split('.');
        let fieldIndex = {};
        if (sheetName) {
            const parent = this.parent();
            if (parent && parent.workbook) {
                const sheet = parent.workbook.getSheetFromName(sheetName);
                if (sheet && fieldOrDetail) {
                    const tableName = fieldOrDetail.replace('_', '');
                    const table = sheet.tables.findByName(tableName);
                    if (table) {
                        const bindingPath = table.bindingPath();
                        if (bindingPath) {
                            const { row, colCount, rowCount, col } = table.dataRange();
                            for (let i = 0; i < colCount; i++) {
                                const columnDataField = table.getColumnDataField(i);
                                if (columnDataField == detailField) {
                                    if (detailRow)
                                        fieldIndex = { sheet: sheet, row: row + Number(detailRow), col: col + i };
                                }
                            }
                        }
                    }
                    if (!(detailRow && detailField)) {
                        const { data } = sheet.toJSON();
                        if (data) {
                            const { dataTable } = data;
                            if (dataTable) {
                                each(dataTable, (o, rowIndex) => {
                                    each(o, (obj, colIndex) => {
                                        const bindingPath = sheet.getBindingPath(rowIndex, colIndex);
                                        if (bindingPath) {
                                            if (bindingPath == fieldName) {
                                                fieldIndex = { sheet: sheet, row: Number(rowIndex), col: Number(colIndex) };
                                            }
                                        }
                                    });
                                });
                            }
                        }
                    }
                }
            }

        }
        return fieldIndex;
    }

    // 弹出数据集合窗口
    openDataset = () => {
        window.open("/spa/edc/static4engine/report/engine.html#/edcreportengine/dataset");
    }
}